<template>
  <div>
      <van-nav-bar
        v-if="this.buttonadd==2"
        title="修改应用"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      />
      <van-nav-bar
        v-else
        title="新增应用"
        left-text="返回"
        left-arrow
        @click-left="onClickLeft"
      />
    <van-form @submit="onSubmit" @failed="onFailed">
      <van-field
        v-model="form.strAppname"
        name="strAppname"
        label="应用名称"
        placeholder="应用名称"
        :rules="[
          { required: true, message: '请填写应用名称' },
          {pattern:/^[\u4E00-\u9FA5A-Za-z0-9]+$/,message:'请不要输入特殊符号'}
        ]"
      />
      <van-field
        readonly
        clickable
        name="iApptype"
        label="应用类型"
        :value="iApptype"
        placeholder="选择应用类型"
        @click="showPicker1('应用类型', 'iApptype')"
        :rules="[{ required: true, message: '请填写应用类型' }]"
      />
      <van-field
        v-if="form.iApptype==2"
        v-model="form.strPackagename"
        name="strPackagename"
        label="应用包名"
        placeholder="请填写应用包名(例:com.jdk.com)"
        :rules="[{ required: true, message: '请填写应用包名(例:com.jdk.com)' }]"
      />
      <van-field
        v-if="form.iApptype==3"
        v-model="form.strPackagename"
        name="strPackagename"
        label="链接地址"
        placeholder="请填写链接地址"
        :rules="[
          { required: true, message: '请填写链接地址' },
          { pattern:/^((ht|f)tps?):\/\/[\w\-]+(\.[\w\-]+)+([\w\-.,@?^=%&:\/~+#]*[\w\-@?^=%&\/~+#])?$/, message: '地址必须以http/https/ftp/ftps开头' }
        ]"
      />
      <van-field
        v-if="buttonadd===1"
        v-model="form.strParorgnum"
        readonly
        name="strParorgnum"
        label="所属机构"
        placeholder="选择所属机构"
        @click="checkOrgs"
        :rules="[{ required: true, message: '选择所属机构' }]"
      />
      <van-field
        v-else
        disabled
        v-model="form.strParorgnum"
        name="strParorgnum"
        label="所属机构"
        placeholder="选择所属机构"
        @click="checkOrgs"
      />

      <van-popup v-model="show">
        <div class="container">
          <van-search
            v-model="searchform.iOrgname"
            show-action
            placeholder="请输入机构名称"
            @search="onSearch"
          >
            <template #action>
              <div @click="onSearch">搜索</div>
            </template>
          </van-search>
          <div class="list-container">
            <div class="section">
              <p v-if="listData.length===0" class="yyp">
                <van-empty description="暂无数据~"/>
              </p>
              <van-swipe-cell v-else>
                <van-checkbox-group v-model="refApp">
                  <van-checkbox v-for="(item,index) in listData" :name="item" :key="index">
                    <div class="yycard">
                      <div class="yycard_p">
                        <p>{{item.strOrgname}}</p>
                      </div>
                    </div>
                  </van-checkbox>
                </van-checkbox-group>
              </van-swipe-cell>
            </div>
            <div class="bottom">
              <div v-if="listData.length>0" type="primary" class="addbtn" block @click="submitcheck()">添加</div>
            </div>
          </div>
        </div>
      </van-popup>


      <van-field
        v-model="form.strDetail"
        name="strDetail"
        rows="2"
        autosize
        label="留言"
        type="textarea"
        maxlength="128"
        placeholder="请输入留言"
        show-word-limit
      />
      <van-field name="uploader" label="图片上传" :rules="[{ required: true, message: '请上传图片' }]">
        <van-uploader

          slot="input"
          v-model="fileList"
          @oversize="onOversize"
          :after-read="afterRead"
          accept="image/*"
          :max-count="1"
        >
        </van-uploader>
      </van-field>
      <div style="margin-top: 30px;">
        <van-button type="primary" native-type="submit">确认</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
  import {getselectList, addInfo, editInfo, getOrgList} from '../../api/application'
  import axios from 'axios'
  import {Toast} from "vant";

  export default {
    name: 'addApplication',
    data() {
      return {
        buttonadd: '',
        dialogStatus: '',
        show: false,
        fileList: [],//图片
        listData: [], //机构列表
        refApp: [],

        //范围机构编号搜索
        searchform: {
          iOrgname: '',
          iOrgsysnum: localStorage.getItem('iOrgsysnum')
        },
        // 新增应用页面表单
        form: {
          iApptype: '',
          strAppname: '',
          strCover: '',
          strPackagename: '',
          strDetail: '',
          valArr: '',
          iOrgsysnum: localStorage.getItem('iOrgsysnum'),
          strOperator: localStorage.getItem('iUsersysnum'),
          /*iStatus: '',
          iAppnum: '',*/
          deviceType: '1',
          strParorgnum: '',
          id: ''
        },
        showPicker: false,
        orgList: [],
        iApptype: ''
      }
    },
    created() {
      //buttonadd = 1 新增;buttonadd = 2 修改
      this.buttonadd = JSON.parse(this.$route.query.buttonadd)

      if (this.buttonadd == 2) {
        //this.form = JSON.parse(this.$route.query.rowAll)
        const routeParams = JSON.parse(this.$route.query.rowAll)
        this.form = {
          iApptype: routeParams.iApptype,
          strAppname: routeParams.strAppname,
          strCover: routeParams.strCover,
          strPackagename: routeParams.strPackagename,
          strDetail: routeParams.strDetail,
          iOrgsysnum: localStorage.getItem('iOrgsysnum'),
          strOperator: localStorage.getItem('iUsersysnum'),
          strParorgnum: routeParams.orgnames,  //机构名称编号
          valArr: routeParams.orgnums,         //获取的机构编号
          id: routeParams.id
        }
        this.fileList.push({url: this.form.strCover})
        this.iApptype = routeParams.iApptypename
        /* this.form.strParorgnum = this.form.orgnames  //机构名称编号
         this.form.valArr = this.form.orgnums         //获取的机构编号*/
      }
      this.getTypesys()
    },
    methods: {
      //范围机构弹窗
      checkOrgs() {
        this.show = true;
        this.fetchData()
      },
      //头部返回
      onClickLeft() {
        this.$router.go(-1)
      },

      //头部右边按钮
      onClickRight() {
        Toast('按钮')
      },

      //机构弹窗搜索
      onSearch() {
        this.fetchData()
      },

      //获取机构编号列表
      fetchData() {
        getOrgList(this.searchform).then(res => {
          this.listData = res.orgList
        })
      },

      //机构弹窗添加按钮
      submitcheck() {
        let orgArr = []
        let orgnumArr = []
        console.log(this.refApp)
        this.refApp.forEach((item, index) => {
          orgArr.push(item.strParorgnum)
          orgnumArr.push(item.iOrgsysnum)
        });
        this.form.strParorgnum = orgArr.join(',')
        this.form.valArr = orgnumArr
        this.show = false
      },

      //获取应用类型
      getTypesys() {
        getselectList({iType: 5}).then(res => {
          this.orgList = res.sysparamList
        })
      },

      //应用类型所选弹框
      showPicker1(title, name) {
        let data1 = []
        this.orgList.filter(item => {
          if (item.strCode != -1) {
            data1.push(item)
          }
        })

        if (!this.picker) {
          this.picker = this.$createPicker({
            title,
            data: [data1],
            alias: {
              value: 'strCode',
              text: 'strValue'
            },
            onSelect: (selectedVal, selectedIndex, selectedText) =>
              this.selectHandle(selectedVal, selectedIndex, selectedText, name),
            onCancel: this.cancelHandle
          })
        }
        this.picker.show()
      },

      //选中的值已供提交
      selectHandle(selectedVal, selectedIndex, selectedText, name) {
        this.form[name] = selectedVal[0]
        this[name] = selectedText[0]
        this.picker = null
      },

      //取消弹窗
      cancelHandle() {
        this.picker = null
      },

      //新增/修改应用提交
      onSubmit(values) {
        this.form.Type = 1
        this.form.deviceType = 1
        let newObj = Object.assign(values, this.form)
        delete newObj.uploader
        if (this.buttonadd === 1) {   //buttonadd === 1 新增
          addInfo(newObj).then(res => {
            this.$router.push({path: 'list'})
          })
        } else {
          editInfo(newObj).then(res => {   //修改
            this.$router.push({path: 'list'})
          })
        }

      },

      //失败
      onFailed(errorInfo) {
        console.log('failed', errorInfo)
      },

      //点击机构编号跳转
      checkOrg() {
        this.$router.push({path: 'SearchOrg'})
      },

      //图片上传
      afterRead(file) {
        file.status = 'uploading'
        file.message = '上传中...'

        // 此时可以自行将文件上传至服务器
        let content = file.file
        let data = new FormData()
        data.append('uploadFile', content)

        axios.post('http://192.168.241.200:8888/system/fileRequest', data).then(res => {
          // let datas = res.data.datas.path;
          console.log(res.data.result)
          if (res.data.result.transCode === 'success') {
            this.form.strCover = res.data.result.result.replace(
              '/home/topsales/static',
              'http://192.168.241.200:8888'
            )
            file.status = 'success'
          } else {
            setTimeout(() => {
              file.status = 'failed'
              file.message = '上传失败'
            }, 1000)
          }
        })
      },
      onOversize(file) {
        console.log(file)
      },
      toapplication() {
        this.$router.push('list')
      },

      onConfirm(value, index) {
        this.value = value
        console.log(index)
        this.showPicker = false;
      }
    }
  }
</script>

<style lang="scss" scoped>
  /*机构弹窗里样式*/
  .container {
    height: 100%;

    .list-container {
      display: flex;
      flex-direction: column;

      .section {
        flex: 1;
        height: 280px;
        max-height: 280px;
        overflow: auto;
        padding-bottom: 10px;
      }

      .bottom {
        flex: 1;
        display: flex;
        justify-content: center;
        align-content: center;
        position: fixed;
        bottom: 16px;
        left: 0;
        width: 100%;
        background: #fafafa;

        .van-button {
          width: 90%;
        }
      }
    }
  }

  .yyp {
    text-align: center;
    font-size: 14px;
    color: #8c8a8a;
    line-height: 2;
  }

  .yycard {
    display: flex;
    border-bottom: 1px solid whitesmoke;
    padding: 5px 0;
    margin-left: 20px;
    width: 300px;
    height: 35px;
    align-items: center;
  }

  .yyimg {
    width: 60px;
    height: 60px;
    border-radius: 6px;
    background-color: #F5F7FA;
  }

  .yycard_p {
    font-size: 14px;
    line-height: 20px;
    vertical-align: middle;
    padding-left: 10px;
    color: #6b6b6b;
  }

  .yycard_title {
    font-size: 14px;
    color: #000;
  }

  .van-button--primary {
    background-color: #0c1b35;
    border-color: #0c1b35;
    border-radius: 4px;
    width: 90%;
    margin: 20px;
  }

  .van-button--danger {
    height: 100%;
  }

  .delete-button2 {
    background-color: #6b6b6b;
    border: 1px solid #6b6b6b;
  }

  /deep/ .van-search__content {
    border-radius: 20px;
    background-color: #e7e9ec;
  }

  /deep/ .van-checkbox__icon {
    position: relative;
    left: 25px;
  }

  .ellipsisp {
    width: 300px;
  }

  /*详情页面样式*/
  .uploadImg {
    display: flex;
    padding: 16px;
    align-items: center;
    align-self: start;
    justify-content: space-around;

    span {
      flex: 1;
      font-size: 14px;
    }
  }

  .van-uploader__wrapper {
    flex-wrap: nowrap;
  }

  /deep/ .van-button--primary {
    color: #fff;
    background-color: #0c1b35;
    border: 0.02667rem solid #0c1b35;
    border-radius: 4px;
    height: 40px;
    width: 90%;
    margin: 0 20px 3px 20px;
  }

  /deep/ .van-popup--center {
    top: 30%;
    left: 0;
    -webkit-transform: none;
    transform: none;
    width: 100%;
    height: 100%;
  }

  .addbtn {
    color: #fff;
    background-color: #0c1b35;
    border: 0.02667rem solid #0c1b35;
    border-radius: 0.10667rem;
    width: 90%;
    margin: 0 0.53333rem 0.08rem 0.53333rem;
    text-align: center;
    font-size: 16px;
    padding: 10px 0;
  }
</style>
